package com.hanserwei.han_picture.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.domain.entity.vo.PictureVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Jackson配置测试控制器
 * 用于验证JacksonConfiguration是否在不同场景下生效
 *
 * @author hanserwei
 */
@RestController
@RequestMapping("/jackson-test")
@RequiredArgsConstructor
@Tag(name = "JacksonConfigurationTest")
@Slf4j
public class JacksonConfigTestController {

    private final ObjectMapper objectMapper;

    @Operation(summary = "测试JacksonConfiguration是否生效")
    @GetMapping("/test-jackson-config")
    public ApiResponse<Map<String, Object>> testJacksonConfig(
            @RequestParam(defaultValue = "1234567890123456789") Long testId) {

        try {
            Map<String, Object> result = new HashMap<>();

            // 1. 测试HTTP接口返回的Long类型（Spring MVC自动序列化）
            result.put("httpTest_longValue", testId);
            result.put("httpTest_longValue2", testId + 1);

            // 2. 测试手动使用ObjectMapper序列化（模拟WebSocket场景）
            Map<String, Object> testData = new HashMap<>();
            testData.put("id", testId);
            testData.put("userId", testId + 1);
            testData.put("message", "测试消息");

            String manualJson = objectMapper.writeValueAsString(testData);
            result.put("manualSerializedJson", manualJson);

            // 3. 验证手动序列化的结果
            boolean idAsString = manualJson.contains("\"id\":\"" + testId + "\"");
            boolean userIdAsString = manualJson.contains("\"userId\":\"" + (testId + 1) + "\"");

            result.put("manual_idAsString", idAsString);
            result.put("manual_userIdAsString", userIdAsString);

            // 4. 测试PictureVO序列化
            PictureVO pictureVO = new PictureVO();
            pictureVO.setId(testId);
            pictureVO.setUserId(testId + 1);
            pictureVO.setName("测试图片");

            String pictureVOJson = objectMapper.writeValueAsString(pictureVO);
            result.put("pictureVOJson", pictureVOJson);

            boolean pictureIdAsString = pictureVOJson.contains("\"id\":\"" + testId + "\"");
            boolean pictureUserIdAsString = pictureVOJson.contains("\"userId\":\"" + (testId + 1) + "\"");

            result.put("pictureVO_idAsString", pictureIdAsString);
            result.put("pictureVO_userIdAsString", pictureUserIdAsString);

            // 5. 总结测试结果
            if (idAsString && userIdAsString && pictureIdAsString && pictureUserIdAsString) {
                result.put("jacksonConfigStatus", "SUCCESS - JacksonConfiguration配置在所有场景下都生效");
            } else {
                result.put("jacksonConfigStatus", "PARTIAL - JacksonConfiguration配置在某些场景下未生效");
            }

            result.put("conclusion", "HTTP接口返回的Long值会被Spring MVC自动序列化为字符串，手动使用ObjectMapper的结果应该与HTTP接口一致");

            log.info("Jackson配置测试 - 测试ID: {}, 手动序列化: {}", testId, manualJson);

            return ApiResponse.success("Jackson配置测试完成", result);

        } catch (Exception e) {
            log.error("Jackson配置测试失败", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", e.getMessage());
            return ApiResponse.success("测试失败: " + e.getMessage(), errorResult);
        }
    }

    @Operation(summary = "直接返回包含Long字段的对象")
    @GetMapping("/test-direct-long")
    public ApiResponse<PictureVO> testDirectLong(@RequestParam(defaultValue = "1234567890123456789") Long testId) {
        PictureVO pictureVO = new PictureVO();
        pictureVO.setId(testId);
        pictureVO.setUserId(testId + 1);
        pictureVO.setName("测试图片");
        pictureVO.setUrl("https://example.com/test.jpg");

        // 这个PictureVO会被Spring MVC直接序列化返回
        // 如果JacksonConfiguration生效，Long字段应该被序列化为字符串
        return ApiResponse.success("直接返回PictureVO测试", pictureVO);
    }

    @Operation(summary = "测试LocalDateTime序列化和反序列化")
    @PostMapping("/test-datetime")
    public ApiResponse<Map<String, Object>> testDateTime(@RequestBody Map<String, Object> requestData) {
        try {
            Map<String, Object> result = new HashMap<>();

            // 1. 测试反序列化 - 从JSON字符串解析LocalDateTime
            String dateTimeStr = (String) requestData.get("dateTime");
            if (dateTimeStr != null) {
                // 使用ObjectMapper反序列化
                String json = "{\"dateTime\":\"" + dateTimeStr + "\"}";
                @SuppressWarnings("unchecked")
                Map<String, Object> parsed = objectMapper.readValue(json, Map.class);
                result.put("parsedDateTime", parsed.get("dateTime"));
                result.put("parsedDateTimeType", parsed.get("dateTime").getClass().getSimpleName());
            }

            // 2. 测试序列化 - 将LocalDateTime序列化为JSON
            LocalDateTime now = LocalDateTime.now();
            LocalDate today = LocalDate.now();

            Map<String, Object> testData = new HashMap<>();
            testData.put("currentDateTime", now);
            testData.put("currentDate", today);
            testData.put("message", "时间测试");

            String serializedJson = objectMapper.writeValueAsString(testData);
            result.put("serializedJson", serializedJson);

            // 3. 验证序列化格式
            boolean hasCorrectDateTimeFormat = serializedJson.contains("\"currentDateTime\":\"") &&
                    serializedJson.matches(".*\"currentDateTime\":\"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\".*");
            boolean hasCorrectDateFormat = serializedJson.contains("\"currentDate\":\"") &&
                    serializedJson.matches(".*\"currentDate\":\"\\d{4}-\\d{2}-\\d{2}\".*");

            result.put("hasCorrectDateTimeFormat", hasCorrectDateTimeFormat);
            result.put("hasCorrectDateFormat", hasCorrectDateFormat);

            // 4. 测试完整的反序列化
            @SuppressWarnings("unchecked")
            Map<String, Object> deserialized = objectMapper.readValue(serializedJson, Map.class);
            result.put("deserializedDateTime", deserialized.get("currentDateTime"));
            result.put("deserializedDate", deserialized.get("currentDate"));

            if (hasCorrectDateTimeFormat && hasCorrectDateFormat) {
                result.put("datetimeConfigStatus", "SUCCESS - LocalDateTime和LocalDate配置正确");
            } else {
                result.put("datetimeConfigStatus", "FAILED - 日期时间格式配置有问题");
            }

            log.info("LocalDateTime测试完成 - 序列化结果: {}", serializedJson);

            return ApiResponse.success("LocalDateTime配置测试完成", result);

        } catch (Exception e) {
            log.error("LocalDateTime配置测试失败", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", e.getMessage());
            errorResult.put("errorType", e.getClass().getSimpleName());
            return ApiResponse.success("测试失败: " + e.getMessage(), errorResult);
        }
    }
}
